package com.atguigu.gulimall.ware.dao;

import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 商品库存
 * 
 * @author xiaolei
 * @email qingyulei@yeah.net
 * @date 2020-08-23 00:17:08
 */
@Mapper
public interface WareSkuDao extends BaseMapper<WareSkuEntity> {

    @Update("UPDATE `wms_ware_sku` SET stock=stock+#{skuNum} WHERE sku_id=#{skuId} AND ware_id=#{wareId}")
    void addStock(@Param("skuId") Long skuId, @Param("wareId") Long wareId, @Param("skuNum") Integer skuNum);

    @Select("SELECT COUNT(stock-stock_locked) FROM `wms_ware_sku` WHERE sku_id = #{skuId}")
    Long getSkuStock(Long skuId);

    @Select("SELECT\n" +
            "            ware_id\n" +
            "        FROM\n" +
            "            wms_ware_sku\n" +
            "        WHERE\n" +
            "            sku_id = #{skuId}\n" +
            "          AND stock - stock_locked > 0")
    List<Long> listWareIdHasSkuStock(Long skuId);

    @Update("UPDATE wms_ware_sku\n" +
            "        SET stock_locked = stock_locked + #{num}\n" +
            "        WHERE\n" +
            "            sku_id = #{skuId}\n" +
            "          AND ware_id = #{wareId}\n" +
            "          AND stock - stock_locked >= #{num}")
    Long lockSkuStock(Long skuId, Long wareId, Integer num);
}
